---
title: "Some Data Visualization"
author: "Colin Kuehl"
format: html
geometry: margin=1in
fontfamily: libertine
fontsize: 11pt
editor_options:
  chunk_output_type: console
---

```{r}
#| label: setup
#| include: false

knitr::opts_chunk$set(cache=TRUE,
 message=FALSE, warning=FALSE,tidy.opts=list(width.cutoff=80), tidy= TRUE)
```

Welcome to data visualization

# Section 1

First, while we have used QMD/Rmarkdown all semester we have not discussed their value as a word processer.

There are all sorts of things you can in Markdown.

- [Quarto Official Documentation](https://quarto.org/docs/guide/)
- [Quarto: The Practical Guide](https://quarto-tdg.org/)
- [Making Shareable Documents with Quarto](https://openscapes.github.io/quarto-website-tutorial/)
- [Quarto for Reproducible Research & Academic Publishing](https://elenlefoll.quarto.pub/quarto4research/)
- [Awesome Quarto — Curated Resources List](https://github.com/mcanouil/awesome-quarto)
- [Quarto on Posit Open Source](https://opensource.posit.co/software/quarto/)

Or insert an image

![I love R](https://www.r-project.org/logo/Rlogo.png){width="50%"}

You can write your text *italics* or make things **bold**

You can even use it create citations, but we won't get into that today.

As you've learned (probably the hard way), a key with Rmarkdown is to continuously knit to make sure you are not making mistakes and look at what the output looks like.

```{r}
#| include: false

library(tidyverse)
library(ggplot2)
library(ggthemes)
```

# Some thoughts on Visualization

Visualizing quantitative data is critical to scientific work and moving beyond basics can enhance the quality of any work that you do. Even if you are relying primarily on qualitative work a few well done figures can add tremendous value to your work.

As you read in the Healy book, there aren't many hard and fast rules when it comes to visualization.

My quick thoughts:[^1]

[^1]: Cool a footnote. These are mostly just my musings.

1.  Keep it simple - only display data critical to your argument. Less can be more
2.  Fully label -

- Include axis
- Interpret in your text

3.  Have a clear idea of what you want your reader to get out of each figure. Remember, they don't know the data like you do.
4.  Be cognizant of scales
5.  Most journals still publish in greyscale and many people are colorblind so you can't rely too much on color variation.
6.  The best way to get good at visualizations is to practice.

"The greatest value of a picture is when it forces us to notice what we never expected to see." — John Tukey

You will use data visualizations in two ways. First, is to get know your own data. There will be lots of these graphs and they don't need to be "bedazzled." Second, is the actual figures you want to use for public consumption. As with models, you'll end up using a small portion of all the figures you use so make them good.

### GGplot

We've already worked in GGplot this semester and for good reason. It is the premier package for creating figures (even compared to other software systems). Almost all figures I now produce for publication use GGplot. Whether we knew it or not there is underlying *"grammar of graphics"* that [ggplot uses](https://r4ds.had.co.nz/data-visualisation.html#the-layered-grammar-of-graphics).

ggplot(data = <DATA>) + <GEOM_FUNCTION>( mapping = aes(<MAPPINGS>), stat = <STAT>, position = <POSITION> ) + <COORDINATE_FUNCTION> + <FACET_FUNCTION>

- data is a data frame
- Aesthetics is used to indicate x and y variables. It can also be used to control the color, the size or the shape of points, the height of bars, etc…..
- Geometry corresponds to the type of graphics (histogram, box plot, line plot, density plot, dot plot, ….)
- Others are optional

There are a wide variety of graphs you can create in [ggplot](https://r-graph-gallery.com/). However, the ones we have used throughout the semester histograms or density plots, scatterplots(with and without regression lines), bar plots, and box plots will be 90% of the figures that you use. For each variable of interest you should know its distribution(histogram or boxplot). For each relationship, you should know how it plots.

Rather than going through a bunch of examples lets talk through an example. What is good and bad about this figure?

```{r}
#| echo: false

ggplot(mpg, aes(displ, hwy)) +
  geom_point(aes(color = class)) +
  geom_smooth(se = FALSE) +
  labs(title = "Fuel efficiency generally decreases with engine size")+theme_bw()
```

Create a better version:

```{r}

```

# Mapping

## Mapping Specific Locations

```{r}
#| echo: false

#install.packages(c("sf", "mapview", "leaflet", "usmap", "rworldmap"))


library(sf)
library(mapview)
library(readr)
library(leaflet)

starbucks <- read_csv("https://raw.githubusercontent.com/libjohn/mapping-with-R/master/data/All_Starbucks_Locations_in_the_US_-_Map.csv")
```

We can create a map of Starbucks locations

```{r}
#| echo: false

mapview(starbucks, xcol = "Longitude", ycol = "Latitude", crs = 4269, grid = FALSE)
```

## State Maps

```{r}
#| echo: false

library(usmap) #https://cran.r-project.org/web/packages/usmap/vignettes/mapping.html
library(ggplot2)

plot_usmap(regions = "counties") +
  labs(title = "US Counties",
       subtitle = "This is a blank map of the counties of the United States.") +
  theme(panel.background = element_rect(color = "black", fill = "lightblue"))


starbucksstate <- starbucks %>% count(State)
starbucksstate$state <- starbucksstate$State

states <- left_join(statepop, starbucksstate,by=c("abbr"="state"))

states$percap <- states$pop_2022/states$n

plot_usmap(data = states, values = "n")+ scale_fill_continuous(
    low = "white", high = "darkgreen", name = "# of Starbucks Locations", label = scales::comma
  ) + theme(legend.position = "right")+ labs(title = "Starbucks Across the United States")

plot_usmap(data = states, values = "percap")+ scale_fill_continuous(
    low = "white", high = "darkolivegreen", name = "Population (2015)", label = scales::comma
  ) + theme(legend.position = "right")+labs(title = "Starbucks Per Capita")
```

# Look at Dunkin Donuts

```{r}
#| echo: false

dunkin <- read_csv("https://raw.githubusercontent.com/trendct/dunkin-donuts-ct/master/dunkindonuts.csv")

mapview(dunkin, xcol = "lng", ycol = "lat", crs = 4269, grid = FALSE)

dunkinstate <- dunkin %>% count(state)


states <- left_join(states, dunkinstate,by=c("abbr"="state"))


plot_usmap(data = states, values = "n.y")+ scale_fill_continuous(
    low = "white", high = "orange", name = "# of dunkin Locations", label = scales::comma
  ) + theme(legend.position = "right")+ labs(title = "dunkin Across the United States")
```

## Global Maps

```{r}
#| echo: false
#| message: false
#| warning: false

#install.packages(c('gapminder',,'gganimate','gifski', 'rworldmap', 'gganimate'))

library(gapminder)#dataset
library(rworldmap)

#summary(gapminder)
#dim(gapminder)

gapmap <-joinCountryData2Map(gapminder,joinCode="ADMIN", nameJoinColumn="country")
par(mai=c(0,0,0.2,0),xaxs="i",yaxs="i") #Trying to use gapminder data(not all seem to convert. could use countrycode to convert to ISO3)

mapCountryData(gapmap, nameColumnToPlot="lifeExp",  mapTitle="Life Expectancy", addLegend=TRUE)

mapCountryData(gapmap, nameColumnToPlot="gdpPercap",  mapTitle="GDP per Capita", colourPalette="rainbow", addLegend=TRUE)#don't use this colour palette
```

# Animation

Scatterplot

```{r}
#| echo: false

ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
   geom_point(alpha = 0.7, show.legend = FALSE) +
   scale_colour_manual(values = country_colors) +
   scale_size(range = c(2, 12)) +
   scale_x_log10() +
   facet_wrap(~continent) +
   labs(title = 'Year: 1952-2007', x = 'GDP per capita', y = 'Life expectancy')
```

You can also add R code mid-text. For example, the average GDP per capita is `r mean(gapminder$gdpPercap)`

Create animation

```{r}
#| echo: false

library(gganimate)

p1 <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
             geom_point(alpha = 0.7, show.legend = FALSE) +
             scale_colour_manual(values = country_colors) +
             scale_size(range = c(2, 12)) +
             scale_x_log10()  +
  facet_wrap(~continent) +
             # Animating the plot
             labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'Life expectancy') +
             transition_time(year) +
             ease_aes('linear')

animate(p1)
anim_save('plot_gdpPercap_lifeExp.gif')

#World Together
p2 <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop, colour = country)) +
             geom_point(alpha = 0.7, show.legend = FALSE) +
             scale_colour_manual(values = country_colors) +
             scale_size(range = c(2, 12)) +
             scale_x_log10()  +
             # Animating the plot
             labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'Life expectancy') +
             transition_time(year) +
             ease_aes('linear')
animate(p2)
```

Challenge create a map or animation using your final project data:

```{r}

```

We'll play some more tomorrow
